package com.tech.algorithm.linked;

/**
 * @Description: 实现链表的增、删、改、查方法
 * @Author: zl
 * @Date: 2019/8/4 16:15
 */
public class Link {
    private int count = 0;
    private int foot = 0;

    /**
     * 定义一个节点类
     */
    private class Node {
        private Object data;//数据
        private Node next;//下一个节点的指针

        public Node(Object data) {
            this.data = data;
        }

        public void addNode(Node newNode) {
            if (this.next == null) {
                this.next = newNode;
            } else {
                this.next.addNode(newNode);
            }
        }

        // 获取指定下标节点数据
        public Object getNode(int index) {
            if (Link.this.foot++ == index) {
                return this.data;
            } else {
                return this.next.getNode(index);
            }

        }

        // 修改指定下标的数据内容
        public void setNode(int index, Object obj) {
            if (Link.this.foot++ == index) {
                this.data = obj;
            } else {
                this.next.setNode(index, obj);
            }
        }
    }

    private Node root;//根节点

    // 增
    public void add(Object obj) {
        if (obj == null)
            return;

        //step1 构造根节点
        Node newNode = new Node(obj);
        if (this.root == null) {
            this.root = newNode;
        } else {
            this.root.addNode(newNode);
        }
        this.count++;
    }

    // 链表大小
    public int size() {
        return count;
    }

    // 是否为空
    public boolean isEmpty() {
        return this.root == null;
    }

    // 获取指定的列表
    public Object get(int index) {
        if (index > this.count - 1) {
            return null;
        }
        this.foot = 0;
        return this.root.getNode(index);
    }

    // 修改指定下标内容
    public void set(int index, Object obj) {
        if (index > this.count - 1)
            return;
        this.foot = 0;
        this.root.setNode(index, obj);
    }


    public static void main(String[] args) {
        Link link = new Link();
        link.add("a");
        link.add("b");
        link.add("c");
        link.add("d");
        link.add(null);
        System.out.println(link.get(1));
    }

}
